﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Xml.Linq;
using tnet.Controls.Lookless;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;

namespace CheckNewsItemTask
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;
        private String _BlogRSS = "http://208.113.144.166/?feed=rss2";
        private String LastDateValue = "";
        private int _NewsCounter = 0;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }
         
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        { 
            LastDateValue = Tools2.GetSetting("LastDateValue");

            _NewsCounter = int.Parse(Tools2.GetSetting("_NewsCounter"));
            if (_NewsCounter < 0)
            {
                Tools2.SaveSetting("_NewsCounter", "0");
            }
             
            WebClient TwitterClient = new WebClient();
            TwitterClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ResponseHandler);
            TwitterClient.DownloadStringAsync(new Uri(_BlogRSS)); 
        }

        private void ResponseHandler(object Sender, DownloadStringCompletedEventArgs e)
        { 
            String CurrentParseDate = String.Empty; 

            DateTime LastDate = new DateTime();
            if (!(String.IsNullOrEmpty(LastDateValue)))
            {
                LastDate = DateTime.Parse(LastDateValue);
            }

            #region xml

            XElement _xml;
            System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
            try
            {
                if (!e.Cancelled)
                {
                    _xml = XElement.Parse(e.Result); 

                    foreach (XElement value in _xml.Elements("channel"))
                    {
                        // getdate this data was published
                        CurrentParseDate = value.Element("lastBuildDate").Value;
                        DateTime CurrrentDate = DateTime.Parse(CurrentParseDate);
                         
                        // is it new date?
                        if (LastDateValue != CurrentParseDate)
                        { 
                            _NewsCounter++;

                            Tools2.SaveSetting("_NewsCounter", _NewsCounter.ToString());

                            SetTiles(_NewsCounter);
                        }

                        break; 
                    }
                }

                // for debugging
                //_NewsCounter++; 
                //Tools2.SaveSetting("_NewsCounter", _NewsCounter.ToString()); 
                //SetTiles(_NewsCounter);

                Tools2.SaveSetting("LastDateValue", CurrentParseDate);
                Tools2.SaveSetting("LastDateResults.xml", e.Result);
            }
            catch(Exception) { }
            #endregion

            NotifyComplete();
        }

        private void SetTiles( int RefCounter )
        {  
            // default tile
            ShellTile TileToFind = ShellTile.ActiveTiles.First();

            if (TileToFind != null)
            {
                StandardTileData NewTileData = new StandardTileData();
                NewTileData.Count = RefCounter;
                TileToFind.Update(NewTileData);
            } 

            // the call tile or 2nd tile
            ShellTile SecondTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("/MainPage.xaml?Task=2"));

            if (SecondTile != null)
            { 
                StandardTileData NewTileData = new StandardTileData(); 
                NewTileData.Count = RefCounter; 
                SecondTile.Update(NewTileData); 
            }
        }  
    }
}